<template>
    <div>
        <Modal
                v-model="imageModal"
                title="插入图片">
            <div>
                <div class="m-b-lg">
                    <h5 class="m-b-md">本地上传</h5>
                    <img-upload :p-dir='pDir' :p-count='-1' @on-success='healthFileSuccess' @on-delete='healthFileDelete' >
                        <a class="btn btn-sm btn-outline-primary">本地上传图片</a>
                    </img-upload>
                </div>

                <div>
                    <h5 class="m-b-md">在线图片</h5>
                    <Input v-model="imageUrl" placeholder="在线图片网址"></Input>
                </div>
            </div>
            <div slot="footer">
                <btn-submit class="btn btn-primary" type="button" :p-click="insetImageConfirm">插入图片</btn-submit>
            </div>
        </Modal>
        <textarea ref='html_editor' class='form-control' :name='name'></textarea>
        <c-page-preview ref='page_preview' ></c-page-preview>
    </div>
</template>
<script>
    import {img_whq} from '../../filters/index';
    import Promise from 'promise';
    export default{
        name:'CHtmlEditor',
        props: {
            pData: String,
            pDir: String,
            language: {
                type: String,
                required: false,
                default: "zh-CN"
            },
            height: {
                type: Number,
                required: false,
                default: 160
            },
            minHeight: {
                type: Number,
                required: false,
                default: 160
            },
            maxHeight: {
                type: Number,
                required: false,
                default: 0
            },
            name: {
                type: String,
                required: false,
                default: ""
            },
            toolbar: {
                type: Array,
                required: false,
                default: function() {
                    return [
                        ['fontsize', ['fontsize']],
                        ['height', ['height']],
                        ['style', ['style']],
                        ['font', ['bold', 'italic','underline', 'clear','strikethrough', 'superscript', 'subscript']],
                        ['fontname', ['fontname']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['table', ['hr','table']],
                        ['insert', ['link',/* 'picture',*/ /*'video',*/'image']],
                        ['insert', ['redo','undo']],
                        ['view', ['fullscreen',/* 'codeview',*/ 'preview','help']],
                    ];
                }
            }
        },
        beforeDestroy: function () {
            this.control.summernote('destroy')
        },
        beforeCompile: function() {
            this.control = null;
        },
        data(){
            return {
                imageModal:false,
                imageInsetList:[],
                imageUrl:'',
                videoModal:false,
                videoInsetUrl:''
            }
        },
        mounted(){
            this.init();
        },
        methods: {
            insetImageConfirm(){
                var _self = this;
                return new Promise(function (resolve, reject) {
                    if(!!_self.imageUrl.trim()){
                        if(_self.imageUrl.trim().match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/)){
                            _self.control.summernote('insertImage',_self.imageUrl.trim(), function ($image) {
                                $image.css('max-width','100%');
                            });
                        }
                    }else {
                        _self.imageInsetList.forEach((v,i)=>{
                            _self.control.summernote('insertImage', img_whq(v), function ($image) {
                                $image.css('max-width','100%');
                            });
                            console.log(img_whq(v))
                        });
                    }
                    _self.$set(_self,'imageModal',false);
                    resolve(true);
                })
            },
            healthFileSuccess(data){
                let arr = [];
                data.files.forEach((v)=>{
                    arr.push(v.name)
                });
                this.$set(this,'imageInsetList',arr);
            },
            healthFileDelete(data){
                this.imageInsetList.splice(data.index,1);
            },
            init(){
                //  initialize the summernote
                if (this.minHeight > this.height) {
                    this.minHeight = this.height;
                }
                if(this.maxHeight!=0){
                    if (this.maxHeight < this.height) {
                        this.maxHeight = this.height;
                    }
                }

                var me = this;
                this.control = $(this.$refs['html_editor']);
                this.control.summernote({
                    lang: this.language,
                    height: this.height,
                    minHeight: this.minHeight,
                    maxHeight: this.maxHeight==0?'auto':this.maxHeight,
                    toolbar: this.toolbar,
                    buttons: {
                        image: function (context) {
                            var ui = $.summernote.ui;
                            // create button
                            var button = ui.button({
                                contents: '<i class="note-icon-picture"/>',
                                container: false,
                                tooltip: '图片',
                                click: function () {
                                    me.$set(me,'imageModal',true);
                                }
                            });
                            return button.render();   // return button as jquery object
                        },
                        preview: function (context) {
                            var ui = $.summernote.ui;
                            // create button
                            var button = ui.button({
                                contents: '预览',
                                container: false,
                                tooltip: '预览',
                                click: function () {
                                    me.$refs['page_preview'].handleOpen(me.getContent());
                                }
                            });
                            return button.render();   // return button as jquery object
                        }
                    },
                    callbacks: {
                        onInit: function() {
                            me.control.summernote("code", me.pData);
                        },
                        onChange: function(contents, $editable) {
                            /*$('.note-editable .note-video-clip').each(function(){
                                if(!$(this).hasClass('note-video-wrap')){
                                    $(this).css({
                                        'position':'absolute',
                                        'top':'0',
                                        'left':'0',
                                        'width':'100%',
                                        'height':'100%',
                                    }).addClass('note-video-wrap')
                                            .wrap('<div style="width: 90%;margin: 0 auto"><div style="position: relative;padding-bottom: 55%;width: 100%;"/></div>');
                                }
                            });*/
                        },
                        onImageUpload: function(files) {
                            console.log(files);
                            // upload image to server and create imgNode...
                            //$summernote.summernote('insertNode', imgNode);
                        }
                    }
                });
                /*this.control.on("summernote.change", function() {

                        })
                        .on('summernote.image.upload', function(we, files) {
                            console.log(we, files);
                            // upload image to server and create imgNode...
                            //$summernote.summernote('insertNode', imgNode);
                        });*/
            },
            getContent(){
                var code = this.control.summernote("code");
                var html = (code === null || code.length === 0 ? null : code);
                return html;
            },
        },
        components: {},
        watch:{
            pData(val, oldVal) {
                var code = (val === null ? "" : val);
                this.control.summernote("code", code);
            }
        }
    }
</script>
<style>
    .note-editor.note-frame .note-editing-area .note-editable{
        padding: 20px;
    }
</style>